import { useState, useRef } from 'react';
import { toast } from 'sonner';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { cn } from '@/lib/utils';

export default function Home() {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [ocrResult, setOcrResult] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const recognizeButtonRef = useRef<HTMLButtonElement>(null);
  
  // 文档类型和高级选项状态
  const [documentType, setDocumentType] = useState<string>("general");
  const [showAdvancedOptions, setShowAdvancedOptions] = useState<boolean>(false);
  const [preprocessingOptions, setPreprocessingOptions] = useState({
    grayscale: false,
    contrast: 100, // 100表示原始对比度，范围50-150
    binarization: false,
    denoising: false,
    enhanceResolution: false
  });
  
  // 不同文档类型的默认预处理配置
  const defaultPresets = {
    general: {
      grayscale: false,
      contrast: 100,
      binarization: false,
      denoising: false,
      enhanceResolution: false
    },
    idCard: {
      grayscale: true,    // 身份证适合灰度处理增强文字识别
      contrast: 110,      // 适当提高对比度
      binarization: false, // 身份证不适合二值化，会丢失照片信息
      denoising: false,    // 默认关闭降噪处理
      enhanceResolution: true // 提升分辨率以识别微小文字
    },
    invoice: {
      grayscale: true,    // 发票适合灰度处理
      contrast: 120,      // 提高对比度增强文字清晰度
      binarization: true, // 发票文字清晰，适合二值化处理
      denoising: true,    // 开启降噪处理
      enhanceResolution: false // 发票文字较大，通常不需要提升分辨率
    },
    receipt: {
      grayscale: true,
      contrast: 115,
      binarization: true,
      denoising: true,
      enhanceResolution: true
    },
    contract: {
      grayscale: false,
      contrast: 105,
      binarization: false,
      denoising: false,
      enhanceResolution: true
    },
    airplaneTicket: {
      grayscale: true,     // 飞机票适合灰度处理
      contrast: 115,       // 提高对比度增强文字清晰度
      binarization: true,  // 飞机票文字适合二值化处理
      denoising: true,     // 开启降噪处理
      enhanceResolution: true // 提升分辨率以识别条形码和微小文字
    }
  };
  
  // 应用文档类型默认配置
  const applyDocumentPreset = (type: string) => {
    const preset = defaultPresets[type as keyof typeof defaultPresets] || defaultPresets.general;
    setPreprocessingOptions(preset);
  };
  
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      toast.error('请上传图片文件');
      return;
    }
    
     // 保存文件引用
  setUploadedFile(file);
  
  // 显示预览图
  const reader = new FileReader();
  reader.onload = (event) => {
    setSelectedImage(event.target?.result as string);
    setOcrResult(''); // 重置结果
  };
  reader.readAsDataURL(file);
  
  // 图片上传后自动滚动到识别按钮
  setTimeout(() => {
    recognizeButtonRef.current?.scrollIntoView({ 
      behavior: 'smooth',
      block: 'center' 
    });
  }, 300);
};
  
  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };
  
  const handleOcrSubmit = async () => {
    if (!selectedImage) {
      toast.error('请先上传图片');
      return;
    }
    
    setIsProcessing(true);
     try {
  if (!uploadedFile) {
    toast.error('未找到上传文件');
    setIsProcessing(false);
    return;
  }
  
   // 创建FormData并添加文件和预处理选项
    const formData = new FormData();
   formData.append('file', uploadedFile);
   
   // 添加预处理选项到FormData
   formData.append('grayscale', preprocessingOptions.grayscale ? 'true' : 'false');
   formData.append('contrast', preprocessingOptions.contrast.toString());
   formData.append('binarization', preprocessingOptions.binarization ? 'true' : 'false');
   formData.append('denoising', preprocessingOptions.denoising ? 'true' : 'false');
   formData.append('enhanceResolution', preprocessingOptions.enhanceResolution ? 'true' : 'false');
  
  // 设置请求超时
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 30000); // 30秒超时

  const ocrResponse = await fetch('http://47.107.136.232/free/api/v1/ocrfast', {
    method: 'POST',
    body: formData,
    signal: controller.signal
  });

  clearTimeout(timeoutId);

     if (!ocrResponse.ok) {
    const errorData = await ocrResponse.json().catch(() => null);
    throw new Error(errorData?.message || `OCR识别失败: ${ocrResponse.status} ${ocrResponse.statusText}`);
  }

  const result = await ocrResponse.json();

  // 检查API返回格式
  if (!result || typeof result !== 'object') {
    throw new Error('无效的API响应格式');
  }

  // 尝试多种可能的响应结构
  const extractedText = result.text || result.data?.text || result.content || '';

  if (!extractedText) {
    setOcrResult('未能从图片中识别到文本');
    toast.info('未能从图片中识别到文本');
  } else {
    // 统一处理不同系统的换行符
    const normalizedText = extractedText.replace(/\r\n/g, '\n');
    setOcrResult(normalizedText);
    toast.success('OCR识别成功');
  }
} catch (error) {
     console.error('OCR识别错误:', error);

    if (error.name === 'AbortError') {
      toast.error('请求超时，请重试');
    } else {
      toast.error(error instanceof Error ? error.message : 'OCR识别失败，请重试');
    }
} finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-gradient-to-b from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      <Navbar />

      <main className="flex-grow container mx-auto px-4 py-8 md:py-16">
        <div className="text-center max-w-3xl mx-auto mb-12">
          <h1 className="text-3xl md:text-4xl font-bold text-slate-900 dark:text-white mb-4 tracking-tight">
            在线OCR文字识别 - 免费图片文字提取工具
          </h1>
          <p className="text-lg text-slate-600 dark:text-slate-300 mb-6">
            上传图片，快速识别图片中的文字内容，支持多语言识别，准确率高，完全免费
          </p>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-8">
            <div className="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm">
              <i className="fa-solid fa-bolt text-blue-500 text-xl mb-2"></i>
              <h3 className="font-semibold mb-1">识别速度快</h3>
              <p className="text-sm text-slate-500 dark:text-slate-400">10秒内完成文字识别</p>
            </div>
            <div className="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm">
              <i className="fa-solid fa-check-circle text-green-500 text-xl mb-2"></i>
              <h3 className="font-semibold mb-1">准确率高</h3>
              <p className="text-sm text-slate-500 dark:text-slate-400">先进OCR技术，识别准确率达98%</p>
            </div>
            <div className="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm">
              <i className="fa-solid fa-lock text-purple-500 text-xl mb-2"></i>
              <h3 className="font-semibold mb-1">安全可靠</h3>
              <p className="text-sm text-slate-500 dark:text-slate-400">本地处理，保护您的隐私安全</p>
            </div>
          </div>
        </div>

        {/* 图片上传区域 */}
        <div
          className="border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-2xl p-8 mb-8 transition-all hover:border-blue-500 cursor-pointer bg-white dark:bg-slate-800 shadow-lg hover:shadow-xl transform hover:-translate-y-1"
          onClick={handleUploadClick}
        >
          <div className="text-center">
            <i className="fa-solid fa-cloud-upload text-5xl text-blue-500 mb-4 animate-pulse"></i>
            <p className="text-slate-800 dark:text-white mb-2 font-medium">点击上传图片或拖放至此处</p>
            <p className="text-sm text-slate-500 dark:text-slate-400">支持JPG、PNG格式，大小不超过5MB</p>
            <input
              type="file"
              accept="image/*"
              ref={fileInputRef}
              onChange={handleImageUpload}
              className="hidden"
            />
          </div>
           </div>

           {selectedImage && (
             <div className="text-center mt-4 text-sm text-slate-500 dark:text-slate-400">
               <i className="fa-solid fa-arrow-down-short-wide mr-1"></i> 已自动定位到识别按钮
             </div>
           )}

            {/* 文档类型选择 */}
             <div className="mb-4 overflow-x-auto pb-2">
             <div className="flex space-x-3 min-w-max">
               <button
                 onClick={() => {
                   setDocumentType('idCard');
                   applyDocumentPreset('idCard');
                 }}
                 className={`flex flex-col items-center p-4 rounded-xl transition-all duration-300 ${
                   documentType === 'idCard'
                     ? 'bg-blue-50 dark:bg-blue-900/30 border-2 border-blue-500 dark:border-blue-400 shadow-lg scale-105'
                     : 'bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:shadow-md hover:scale-102'
                 }`}
               >
                 <i className="fa-solid fa-id-card text-2xl mb-2 text-blue-600 dark:text-blue-400"></i>
                 <span className="text-sm font-medium">身份证</span>
               </button>

               <button
                 onClick={() => {
                   setDocumentType('invoice');
                   applyDocumentPreset('invoice');
                 }}
                 className={`flex flex-col items-center p-4 rounded-xl transition-all duration-300 ${
                   documentType === 'invoice'
                     ? 'bg-blue-50 dark:bg-blue-900/30 border-2 border-blue-500 dark:border-blue-400 shadow-lg scale-105'
                     : 'bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:shadow-md hover:scale-102'
                 }`}
               >
                 <i className="fa-solid fa-file-invoice text-2xl mb-2 text-green-600 dark:text-green-400"></i>
                 <span className="text-sm font-medium">发票</span>
               </button>

               <button
                 onClick={() => {
                   setDocumentType('airplaneTicket');
                   applyDocumentPreset('airplaneTicket');
                 }}
                 className={`flex flex-col items-center p-4 rounded-xl transition-all duration-300 ${
                   documentType === 'airplaneTicket'
                     ? 'bg-blue-50 dark:bg-blue-900/30 border-2 border-blue-500 dark:border-blue-400 shadow-lg scale-105'
                     : 'bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:shadow-md hover:scale-102'
                 }`}
               >
                 <i className="fa-solid fa-plane-departure text-2xl mb-2 text-purple-600 dark:text-purple-400"></i>
                 <span className="text-sm font-medium">飞机票</span>
               </button>

              {/* 高级选项图标按钮 */}
              <button
                onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}
                className={`flex items-center justify-center p-4 rounded-xl transition-all duration-300 ${
                  showAdvancedOptions
                    ? 'bg-blue-50 dark:bg-blue-900/30 border-2 border-blue-500 dark:border-blue-400 shadow-lg scale-105'
                    : 'bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:shadow-md hover:scale-102'
                }`}
                aria-label={showAdvancedOptions ? "收起高级选项" : "展开高级选项"}
              >
                 <div className="flex flex-col items-center">
                   <i className="fa-solid fa-sliders text-2xl mb-2 text-blue-500"></i>
                   <span className="text-sm font-medium">更多</span>
                </div>
              </button>
             </div>
           </div>

           {/* 高级选项 */}
           <div className="mb-8">
             <div className={`mt-4 bg-white dark:bg-slate-800 rounded-xl shadow-md p-6 transition-all duration-300 ease-in-out overflow-hidden ${
             showAdvancedOptions ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
           }`}>
             <h3 className="text-lg font-semibold text-slate-800 dark:text-white mb-4 flex items-center">
               <i className="fa-solid fa-sliders mr-2 text-blue-500"></i>图片预处理选项
             </h3>

             <div className="space-y-6">
               {/* 灰度处理 */}
               <div className="flex items-center justify-between">
                 <div>
                   <label className="flex items-center cursor-pointer">
                     <input
                       type="checkbox"
                       checked={preprocessingOptions.grayscale}
                       onChange={(e) => setPreprocessingOptions(prev => ({
                         ...prev,
                         grayscale: e.target.checked
                       }))}
                       className="sr-only peer"
                     />
                     <div className="relative w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer dark:bg-slate-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate-600 peer-checked:bg-blue-600"></div>
                   </label>
                 </div>
                 <div className="flex items-center">
                   <i className="fa-solid fa-adjust text-gray-500 mr-3"></i>
                   <div className="relative group">
                     <span className="text-slate-700 dark:text-slate-300">灰度处理</span>
             <button
              ref={recognizeButtonRef}
                       className="ml-1 text-blue-500"
                       aria-label="查看说明"
                     >ⓘ</button>
                     <div className="absolute z-10 left-full ml-2 mt-1 w-64 bg-slate-800 text-white text-xs p-2 rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                       将彩色图像转换为灰度图像，减少颜色干扰，提高文字识别准确性。适用于大多数文档类型。
                     </div>
                   </div>
                   {preprocessingOptions.grayscale && (
                     <span className="ml-2 text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 px-2 py-0.5 rounded-full">推荐</span>
                   )}
                 </div>
               </div>

               {/* 对比度调整 */}
               <div>
                 <div className="flex items-center justify-between mb-2">
                   <div className="flex items-center">
                     <i className="fa-solid fa-sun text-yellow-500 mr-3"></i>
                     <span className="text-slate-700 dark:text-slate-300">对比度调整</span>
                   </div>
                   <input
                     type="number"
                     min="50"
                     max="150"
                     value={preprocessingOptions.contrast}
                     onChange={(e) => setPreprocessingOptions(prev => ({
                       ...prev,
                       contrast: parseInt(e.target.value) || 100
                     }))}
                     className="w-16 border border-slate-300 dark:border-slate-600 rounded-md px-2 py-1 text-center text-sm"
                   />
                 </div>
                 <input
                   type="range"
                   min="50"
                   max="150"
                   value={preprocessingOptions.contrast}
                   onChange={(e) => setPreprocessingOptions(prev => ({
                     ...prev,
                     contrast: parseInt(e.target.value)
                   }))}
                   className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
                 />
                 <div className="flex justify-between text-xs text-slate-400 mt-1">
                   <span>-50%</span>
                   <span>默认</span>
                   <span>+50%</span>
                 </div>
               </div>

               {/* 二值化处理 */}
               <div className="flex items-center justify-between">
                 <div>
                   <label className="flex items-center cursor-pointer">
                     <input
                       type="checkbox"
                       checked={preprocessingOptions.binarization}
                       onChange={(e) => setPreprocessingOptions(prev => ({
                         ...prev,
                         binarization: e.target.checked
                       }))}
                       className="sr-only peer"
                     />
                     <div className="relative w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer dark:bg-slate-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate-600 peer-checked:bg-blue-600"></div>
                   </label>
                 </div>
                 <div className="flex items-center">
                   <i className="fa-solid fa-th text-gray-700 mr-3"></i>
                   <span className="text-slate-700 dark:text-slate-300">二值化处理</span>
                   <span className="ml-2 text-xs text-slate-400 dark:text-slate-500">(将图片转换为黑白二值)</span>
                 </div>
               </div>

               {/* 降噪处理 */}
               <div className="flex items-center justify-between">
                 <div>
                   <label className="flex items-center cursor-pointer">
                     <input
                       type="checkbox"
                       checked={preprocessingOptions.denoising}
                       onChange={(e) => setPreprocessingOptions(prev => ({
                         ...prev,
                         denoising: e.target.checked
                       }))}
                       className="sr-only peer"
                     />
                     <div className="relative w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer dark:bg-slate-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate-600 peer-checked:bg-blue-600"></div>
                   </label>
                 </div>
                 <div className="flex items-center">
                   <i className="fa-solid fa-wind text-purple-500 mr-3"></i>
                   <span className="text-slate-700 dark:text-slate-300">降噪处理</span>
                   <span className="ml-2 text-xs text-slate-400 dark:text-slate-500">(减少图片噪点干扰)</span>
                 </div>
               </div>

               {/* 提升分辨率 */}
               <div className="flex items-center justify-between">
                 <div>
                   <label className="flex items-center cursor-pointer">
                     <input
                       type="checkbox"
                       checked={preprocessingOptions.enhanceResolution}
                       onChange={(e) => setPreprocessingOptions(prev => ({
                         ...prev,
                         enhanceResolution: e.target.checked
                       }))}
                       className="sr-only peer"
                     />
                     <div className="relative w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer dark:bg-slate-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate-600 peer-checked:bg-blue-600"></div>
                   </label>
                 </div>
                 <div className="flex items-center">
                   <i className="fa-solid fa-search-plus text-green-500 mr-3"></i>
                   <span className="text-slate-700 dark:text-slate-300">提升分辨率</span>
                   <span className="ml-2 text-xs text-slate-400 dark:text-slate-500">(增强图片细节清晰度)</span>
                 </div>
               </div>
             </div>
           </div>
         </div>

         {/* 处理按钮 */}
         {selectedImage && (
           <div className="flex justify-center mb-4">
            <button
              onClick={handleOcrSubmit}
              disabled={isProcessing}
              className={cn(
                "bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-8 rounded-full transition-all shadow-lg hover:shadow-xl transform hover:-translate-y-0.5",
                isProcessing ? "opacity-70 cursor-not-allowed" : ""
              )}
            >
              {isProcessing ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>处理中...
                </>
              ) : (
                "开始识别文字"
              )}
            </button>
          </div>
        )}

        {/* 结果展示区域 */}
         {(selectedImage || ocrResult) && (
           <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 图片预览 */}
            {selectedImage && (
               <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-lg p-3 h-full flex flex-col">
                 <h3 className="text-lg font-semibold text-slate-800 dark:text-white mb-3">上传图片</h3>
                <div className="flex-grow flex items-center justify-center">
                  <img
                    src={selectedImage}
                    alt="预览图"
                    className="max-w-full max-h-[400px] object-contain rounded-lg shadow-inner"
                  />
                </div>
              </div>
            )}

            {/* OCR结果 */}
               <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-lg p-3 h-full flex flex-col">
                 <h3 className="text-lg font-semibold text-slate-800 dark:text-white mb-3">识别结果</h3>
              <div className="flex-grow">
                {isProcessing ? (
                  <div className="flex flex-col items-center justify-center h-full text-slate-500">
                    <i className="fa-solid fa-spinner fa-spin text-3xl mb-4"></i>
                    <p>正在识别图片中的文字...</p>
                  </div>
                ) : ocrResult ? (
                  <div className="h-full overflow-auto p-2 text-slate-700 dark:text-slate-200 whitespace-pre-wrap">
                    {ocrResult}
                  </div>
                ) : (
                  <div className="flex items-center justify-center h-full text-slate-400">
                    <p>识别结果将显示在这里</p>
                  </div>
                )}
              </div>

              {ocrResult && (
                <div className="mt-4 flex justify-end">
                   <button
                     onClick={async () => {
                       try {
                         await navigator.clipboard.writeText(ocrResult);
                         toast.success('识别结果已复制到剪贴板');
                       } catch (err) {
                         console.error('复制失败:', err);
                         toast.error('复制失败，请手动复制');

                         // 备用复制方法
                         const textarea = document.createElement('textarea');
                         textarea.value = ocrResult;
                         document.body.appendChild(textarea);
                         textarea.select();
                         document.execCommand('copy');
                         document.body.removeChild(textarea);
                       }
                     }}
                     className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 flex items-center"
                   >
                     <i className="fa-solid fa-copy mr-1"></i> 复制结果
                  </button>
                </div>
              )}
            </div>
          </div>
        )}
      </main>
      
      <Footer />
    </div>
  );
}